class Scape

Attributes

patches[R]

Public Class Methods

new(patches) click to toggle source
# File lib/scape.rb, line 6
def initialize(patches)
  @patches = patches
  precompute_indices
end

Public Instance Methods

do_time_step() click to toggle source
# File lib/scape.rb, line 11
def do_time_step
  @patches.each do |row|
    row.each do |patch|
      # Update patches
      patch.do_time_step

      # Repopulate depleted patch resources
      replenish_resources(patch)
    end
  end

end
height() click to toggle source
# File lib/scape.rb, line 68
def height
  @patches.empty? ? 0 : @patches.max_by { |x| x.size }.size
end
neighbours(patch, radius) click to toggle source

Locates neighbours in a square pattern within the specified radius Specifying a radius of -1 returns all the patches in the scape

# File lib/scape.rb, line 50
def neighbours(patch, radius)
  if radius == -1
    @flat_patches = patches.flatten if @flat_patches.nil? # Lazy evaluation
    return @flat_patches
  end

  x, y = @indices[patch]
  x0 = [x - radius, 0].max
  x1 = x + radius + 1 # Ruby arrays don't wrap around from the end
  y0 = [y - radius, 0].max
  y1 = y + radius + 1
  @patches.slice(x0, x1).map { |row| row.slice(y0, y1) }.flatten
end
precompute_indices() click to toggle source
# File lib/scape.rb, line 72
def precompute_indices
  @indices = {}
  @patches.each_with_index do |row, x|
    row.each_with_index do |patch, y|
      @indices[patch] = [x, y] if patch
    end
  end
end
replenish_resources(patch) click to toggle source
# File lib/scape.rb, line 24
def replenish_resources(patch)
  patch.resources.each do |resource|
    if resource.depleted? && resource.repopulation_chance > 0
      # For each surrounding patch there is a certain chance the patch will be replenished
      neighbours(patch, 1).each do |neighbour|
        if neighbour.viable?(resource.name) && chance(resource.repopulation_chance)
          resource.repopulate
          break
        end
      end
    end
  end
end
resource_consumption() click to toggle source

Calculates the total amount

# File lib/scape.rb, line 82
def resource_consumption
  counts = {}
  @patches.each do |col|
    col.each do |patch|
      patch.resources.each do |resource|
        counts[resource.name] = counts.fetch(resource.name, 0) + resource.energy_harvested
      end
    end
  end
  counts
end
to_s() click to toggle source
# File lib/scape.rb, line 38
def to_s
  out_string = ""
  @patches.each_with_index do |col, x|
    col.each_with_index do |patch, y|
      out_string << "(#{x}, #{y}): #{patch}\n"
    end
  end
  out_string
end
width() click to toggle source
# File lib/scape.rb, line 64
def width
  @patches.size
end